import { Controller, Get, Query, Post, Body, Inject } from '@nestjs/common';
import { UserService } from './user.service';
import { CaptchaDto } from './dto/captcha.dto';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { JwtService } from '@nestjs/jwt';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Inject(JwtService)
  private jwtService: JwtService;

  @Get('captcha')
  async getCaptcha(@Query() params: CaptchaDto) {
    return await this.userService.getCaptcha(params.username);
  }

  @Post('register')
  async register(@Body() user: RegisterDto) {
    return await this.userService.register(user);
  }

  @Post('login')
  async login(@Body() loginDto: LoginDto) {
    const user = await this.userService.login(loginDto);

    const access_token = this.jwtService.sign(
      {
        userId: user.id,
        username: user.username,
      },
      { expiresIn: '30m' },
    );

    const refresh_token = this.jwtService.sign(
      {
        userId: user.id,
      },
      { expiresIn: '7d' },
    );

    return { access_token, refresh_token };
  }
}
